// index.js
// 获取应用实例
import request from '../../utils/api/request'
import {formatTime} from '../../utils/util'
const app = getApp()
Page({
  data:{
    //默认是创建投票(值为空),值非空就是修改投票
    vote_id:null,
    //0或true为单选,反之
    type:true,
    //标题
    title:'',
    //详细
    titleDetail:'',
    //选项内容
    iconList:[],
    //删除的选项，用于存放删除选项的id
    delIconlist:[],
    iconType: ['cancel'],
    voteSwitch:false,
    spreadSwitch:false,
    //切换的日期
    date: '',
    //切换的时间
    time: '',
    //当前日期时间
    YTD:'',
    minute:'',
  },

  onLoad(options){
   
    //判断是多选还是单选页面
    if ( app.globalData.isRadio ){
      wx.setNavigationBarTitle({title: '创建单选投票'})
      this.setData({
        type: 0
      })
    }else{
      wx.setNavigationBarTitle({title: '创建多选投票'})
      this.setData({
        type: 1
      })
    }
    //非重新编辑投票项
    if ( !options.id){
      this.getDateTime()
      return
    }
    //重新编辑投票项
    this.setData({
      vote_id:options.id
    })
    this.getVoteInfo(options.id)
  },

  //获取投票的详细内容
  async getVoteInfo(vote_id){
    const result = await request(
                          "/api/front/vote/getVote_data",
                          {vote_id}
                         )
    if ( result.err_code == 200 ){
      this.setVoteInfo(result.data)
      return
    }
    wx.showModal({
      title: '错误',
      content: result.message,
      showCancel:false,
    })
  },
  //给投票选项赋值
  setVoteInfo(data){
    let { title,describe,end_time,option,type,anonymous } = data
    console.log(title,describe,option,end_time,type,anonymous)
    console.log(anonymous == '0')
    let date = end_time.split(" ")[0]
    let time = end_time.split(" ")[1]

    //设置页头
    type == '0' ? wx.setNavigationBarTitle({title: '创建单选投票'}) : wx.setNavigationBarTitle({title: '创建多选投票'})

    this.setData({
      title,
      titleDetail:describe,
      iconList:option,
      date,
      time,
      voteSwitch: anonymous == '1' ? false : true,
    })
  },

  //监听标题和标题详细输入
  bindTitleInput(e){
    console.log(e.currentTarget.dataset.prop,e.detail)
    this.setData({
      [e.currentTarget.dataset.prop]: e.detail.value
    })
  },

  //监听选项输入框内容事件
  bindKeyInput(e){
    let id = e.currentTarget.dataset.prop
    this.data.iconList = this.data.iconList.map(item =>{
      if (item.id == id) {
        console.log(item)
        item.content = e.detail.value
        return item
      }
      return  item
    })

  },

  // 切换日期事件
  bindDateChange: function(e) {
    this.setData({
      date: e.detail.value
    })
  },

  // 切换时间事件
  bindTimeChange: function(e) {
    console.log(e.detail.value)
    this.setData({
      time: e.detail.value
    })
  },

  //获取当前日期时间事件
  getDateTime(){
    const date = new Date()
    let year = date.getFullYear()
    let month = date.getMonth()+1  < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1
    let day = date.getDate() < 10 ? '0'+(date.getDate() ) : date.getDate() 
    let YTD =  `${year+1}-${month}-${day}`
    let Hours = date.getHours() < 10 ? '0'+date.getHours() : date.getHours()
    let Minutes = date.getMinutes() < 10 ? '0'+date.getMinutes() : date.getMinutes()
    let minute = Hours +":" + Minutes
    this.setData({
      date:YTD,
      time:minute,
      YTD:`${year}-${month}-${day}`,
      minute
    })
  },

  //添加选项
  addList(){
    let leng = this.data.iconList.length
    let id = 0
    if ( leng != 0){
      id =  this.data.iconList[leng - 1].id+1 
    }
    this.data.iconList.push({id,content:""})
    this.setData({
      iconList:this.data.iconList
    })
  },

  //删除选项
  delItemList(ev){
    let id = ev.currentTarget.dataset.id
    let { iconList } = this.data
    //返回当前删除的数组
    const currentObj = iconList.filter(item => item.id == id )
    //如果当前数组中有投票选项的Id，则不是刚添加的，将其id保存起来，修改api需要这个字段
    currentObj[0].vote_id ? this.data.delIconlist.push(id) : null
    //过滤掉当前删除的元素
    iconList = iconList.filter(item=> item.id != id)
    this.setData({
      iconList
    })
  },

  //是否匿名
  switchChange(){
    this.setData({
      voteSwitch: !this.data.voteSwitch
    })
  },
  //保存
  async saveBtn(){
    //校验数据不通过
    if ( !this.verify() ){
      return
    }
    let { vote_id,title,titleDetail,iconList,type,date,time,voteSwitch,delIconlist} = this.data
    
    //将数组保留: [ {option_id:xx,content:xx} ]格式
    if ( vote_id ){
      iconList = iconList.map( item =>{
        //新添加的选项
        if ( !item.vote_id){
          return {option_id:null,content:item.content}
        } 
        return {option_id:item.id,content:item.content}
        //本来就存在的
      })
    }else{
      //将数组只保留投票项的文字
      iconList = iconList.map( item => item.content)
    }

    let user_id = wx.getStorageSync('userId')
    //发送请求，判断是修改还是创建,true为修改，false为创建
    let result 
    if ( vote_id ){
      // return
      result = await request(
              '/api/front/vote/update_votedata',
              {
                vote_id,
                title,
                describe:titleDetail,
                type:type ? 1 : 0,
                option:iconList,
                start_time:formatTime(new Date()),
                end_time:`${date} ${time}`,
                anonymous: voteSwitch ? 0 : 1,
                delete: delIconlist
              }
            )
    } else{
      result = await request(
        '/api/front/vote/vote_add',
        {
          user_id,
          title,
          describe:titleDetail,
          type:type ? 1 : 0,
          option:iconList,
          end_time:`${date} ${time}`,
          anonymous: voteSwitch ? 0 : 1,
        }
      )
    }


    if( result.err_code == 200){
      wx.showToast({
        title: result.message,
        icon: 'success',
        duration: 2000
      })
     
      this.setData({
        title:null,
        titleDetail:null,
        iconList:[],
        voteSwitch:false,
      })

      //跳转到投票页
      wx.navigateTo({
        url:`/pages/votoDetail/votoDetail?id=${result.data.vote_id}`
      })
      return
    }
    wx.showToast({
      title: result.message,
      icon: 'error',
      duration: 2000
    })

  },

  //校验数据
  verify(){
    const currentDate = new Date()
    let currentMinute = this.data.minute.split(':')
    let saveTime = this.data.time.split(':')
    if (new Date(this.data.date) < new Date(this.data.YTD)) {
      wx.showModal({
        title: '内容有误',
        content: '截止日期不能早于当前时间',
        showCancel:false,
      })
      return
    }
    if ( new Date(this.data.date) <= new Date(this.data.YTD)){
      if(currentDate.setHours(currentMinute[0],currentMinute[1]) > currentDate.setHours(saveTime[0],saveTime[1])){
        // 选择的时间小于当前时间
        wx.showModal({
          title: '内容有误',
          content: '截止日期不能早于当前时间',
          showCancel:false,
        })
        return
      }
    }
    if ( !this.data.title.trim()){
      wx.showModal({
        title: '内容有误',
        content: '标题不能为空',
        showCancel:false,
      })
      return
    }
    const user_id = wx.getStorageSync('userId') || null
    if ( !user_id ){
      wx.showModal({
        title: '内容有误',
        content: '请先登录',
        showCancel:false,
      })
      return
    }
    const iconListArr = this.data.iconList
    //选项有空的
    for (let index = 0; index < iconListArr.length; index++) {
      if ( ! iconListArr[index].content){
        wx.showToast({
          title: '投票项不能为空',
          icon:'none'
        })
        return
      }      
    }
    if (   iconListArr.length == 0 ){
      wx.showToast({
        title: '至少得有一个选项',
        icon:'none'
      })
      return
    }

    //走到最后校验通过
    return true
  }
})
